/**
  普通话等级考试-创建考试
*/
<template>
  <div class="exam-create-container">
    <div v-if="indexKey === 1">
      <el-card shadow="never" v-loading="loading" body-style="padding: 24px;" class="card-margin">
        <h1 class="condition-title">{{$t('mandarin.examList')}}</h1>
        <div class="edu-opertion-bar sub-title">
          <div class="float-right" style="display: flex;">
            <el-button v-if="permitToAdd" type="primary" @click="addExam()">{{$t('common.btn.add')}}</el-button>
          </div>
        </div>
        <edu-table :pagination="false" :order='true' :tooltipEffect="tooltipEffect" stripe :data="dataList" size="mini" @selection-change="handleSelectionChange">
          <edu-table-column :label="$t('subjectCompetitionBase.semester')" prop="calendarYearTerm"></edu-table-column>
          <edu-table-column :label="$t('mandarin.contestTitle')" prop="title"></edu-table-column>
          <edu-table-column :label="$t('mandarin.registrationTime')" prop="signUpTime"></edu-table-column>
          <edu-table-column :label="$t('subjectCompetitionBase.status')" prop="status">
            <template slot-scope="scope">
              <div class="status-container">
                <el-button v-if="scope.row.status === '报名结束'" type="info" plain>{{ scope.row.status }}</el-button>
                <el-button v-else-if="scope.row.status === '未开始'" type="primary" plain>{{ scope.row.status }}</el-button>
                <el-button v-else type="success" plain>{{ scope.row.status }}</el-button>
              </div>
            </template>
          </edu-table-column>
          <edu-table-column :label="$t('common.text.operation')"  fixed="right" min-width="220">
            <template slot-scope="scope">
              <el-button type="text" @click="changeExamEnable(scope.row)">
                <span v-if="scope.row.isEnabled === 1 && permitToClose">{{ $t('subjectCompetitionBase.close') }}</span>
                <span v-if="!scope.row.isEnabled && permitToOpen">{{ $t('subjectCompetitionBase.open') }}</span>
              </el-button>
              <el-button v-if="permitToEdit" type="text" @click="editExam(scope.row)">{{$t('common.btn.edit')}}</el-button>
              <el-button v-if="permitToCountStuRegist" type="text" @click="countStuRegist(scope.row)">{{$t('mandarin.stuRegistStatistics')}}</el-button>
              <el-button v-if="permitToCountCollege" type="text" @click="countCollegeRegist(scope.row)">{{$t('mandarin.collegeRegistStatistics')}}</el-button>
              <el-button  type="text" @click="listSetting(scope.row)">名单设置</el-button>
            </template>
          </edu-table-column>
        </edu-table>
        <el-row type="flex" class="row-bg" justify="end">
          <el-col>
            <el-pagination
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
              :current-page="queryForm.pageNum_"
              :page-sizes="[20, 40, 80, 100]"
              :page-size="queryForm.pageSize_"
              layout="total, sizes, prev, pager, next, jumper"
              :total="queryForm.total_"
              style="float:right;margin-top:10px"
            ></el-pagination>
          </el-col>
        </el-row>
      </el-card>
    </div>
    <!-- 新增/编辑考试开始 -->
    <div v-if="indexKey === 2">
      <operate-exam-create
        :operateMode="operateMode"
        :operateData="operateData"
        :rows="rows"
        @change-exam-create-index="changeExamCreateIndex">
      </operate-exam-create>
    </div>
    <!-- 新增/编辑考试结束 -->
    <!-- 学生报名统计开始 -->
    <div v-if="indexKey === 3">
      <student-regist-statistics :examId="examId" @change-exam-create-index="changeExamCreateIndex()"></student-regist-statistics>
    </div>
    <!-- 学生报名统计结束 -->
    <!-- 学院报名统计  -->
    <div v-if="indexKey === 4">
      <operate-collegeRegistStatistics :examId="examId" @change-exam-create-index="changeExamCreateIndex()"></operate-collegeRegistStatistics>
    </div>
    <el-dialog
      :before-close="beforeClose"
      :title="$t('mandarin.listSet')"
      width="70%"
      class="examination-dialog"
      :visible.sync="dialogVisible"
      :close-on-click-modal="false"
      :close-on-press-escape="false">
      <edit-list-setting :examIdrow="examIdrow" ref="editListSet"
        :editConfirmData="editConfirmData"
        @close-list-setting="closeListSetting"
        @confirm-list-setting="confirmEditListSetting"
        @delete-list-setting="deleteListSetting">
      </edit-list-setting>
    </el-dialog>
  </div>
</template>
<script>
import operateExamCreate from './operateExamCreate';
import studentsRegistStatistics from './studentsRegistStatistics';
import collegeRegistStatistics from './collegeRegistStatistics';
import graduateStudentApi from 'common/src/api/graduateStudent/graduateStudent';
import subjectCompetitionApi from 'common/src/api/subjectCompetition/subjectCompetition';
import editListSetting from './editListSetting';
export default {
  components: {
    'operate-exam-create': operateExamCreate,
    'operate-collegeRegistStatistics': collegeRegistStatistics,
    'student-regist-statistics': studentsRegistStatistics,
    'edit-list-setting': editListSetting
  },
  data () {
    return {
      rows:{},
      auths: [],
      indexKey: 1,
      dialogVisible: false,
      // permitToAdd: true,
      // permitToOpen: true,
      // permitToClose: true,
      // permitToEdit: true,
      // permitToCountStuRegist: true,
      // permitToCountCollege: true,
      permitToAdd: false,
      permitToOpen: false,
      permitToClose: false,
      permitToEdit: false,
      permitToCountStuRegist: false,
      permitToCountCollege: false,
      innerVisible: false,
      multipleSelection: [],
      queryForm: {
        pageNum_: 1,
        pageSize_: 20,
        total_: 0,
        condition: {
          "educationTag": 1,
          "examCategory": 2
        }
      },
      operateMode: 'add',
      operateData: {
        contestTitle: '',
        semester: '',
        registrationStartTime: '',
        registrationEndTime: '',
        listSet: '',
        examExplanation: ''
      },
      dataList: [],
      examId: '',
      examIdrow:'',
      editConfirmData: [],
      deleteIdList: []
    }
  },
  filters: {
    status(val) {
      switch (val) {
        case 0:
          return '报名结束'
        case 1:
          return '正在报名'
        default:
          return val
      }
    }
  },
  created() {
    // 获取当前用户auths权限
    if (localStorage.getItem("sessiondata")) {
      if (JSON.parse(localStorage.getItem("sessiondata")).auths) {
        this.auths = JSON.parse(localStorage.getItem("sessiondata")).auths
      }
    }
    this.onSubmit()
  },
  methods: {
    getListData() {
      subjectCompetitionApi.getPutonghuaExamsList(this.queryForm).then((res) => {
        this.dataList = res.data.list;
        this.queryForm.total_ = res.data.total_;
      })
    },
    onSubmit() {
      this.queryForm.pageNum_ = 1
      this.getListData()
    },
    // 新增考试
    addExam() {
      this.operateMode = 'add'
      for (let key in this.operateData) {
        this.operateData[key] = ''
      }
      this.indexKey = 2
    },
    // 返回列表页
    changeExamCreateIndex() {
      this.indexKey = 1
      this.onSubmit()
    },
    // 编辑考试
    async editExam(row) {
      this.rows=row;
      // let endTime = new Date(row.signUpEnd.replace('-', '/')).getTime()
      // let nowTimeResponse = await graduateStudentApi.getCurrentSystemTime()
      // if (nowTimeResponse.data) {
      //   nowTimeResponse.data = new Date(nowTimeResponse.data).getTime()
      // }
      // if (!(nowTimeResponse.data <= endTime)) {
      //   this.$eduConfirm(this.$t('mandarin.registEndTime') + '（' + row.signUpEnd + '）已过').then(_ => {})
      //   return
      // }
      this.operateMode = 'edit'
      const detailInfo = await subjectCompetitionApi.selectPutonghuaExamDetail({
        id: row.id
      })
      const listInfo = await subjectCompetitionApi.selectRegistRosterNew({
        "pageNum_": 1,
        "pageSize_": 99999,
        "condition": {
          "competitionId": row.id,
          "leaveSchool": null,
          "registrationStatus": null,
          "enrolMethods": null,
          "name": null
        }
      })
      if (detailInfo.code === 200) {
        this.operateData = detailInfo.data
        this.operateData['listSet'] = ''
      }
      if (listInfo.code === 200 && listInfo.data.list.length > 0) {
        let listArray = JSON.parse(JSON.stringify(listInfo.data.list))
        listArray.forEach(item => {
          item["id"] = item.id
          item['name'] = item.studentName
          item['faculty'] = item.college
          item['facultyI18n'] = item.collegeI18n
          item['leaveSchool'] = item.atSchoolStatus
          item['leaveSchoolI18n'] = item.atSchoolStatusI18n
          item['registrationStatus'] = item.studentStatus
          item['registrationStatusI18n'] = item.studentStatusI18n
        })
        this.operateData['listSet'] = listArray
      }
      this.indexKey = 2
    },
    // 开启/关闭考试
    changeExamEnable(row) {
      subjectCompetitionApi.openOrOffPutonghuaExam({
        "id": row.id,
        "isEnabled": row.isEnabled === 0 ? 1 : 0  // 启停状态 0停用 1启用
      }).then(_ => {
        this.onSubmit()
      })
    },
    // 学生报名统计
    countStuRegist(row) {
      this.examId = row
      this.indexKey = 3
    },
    // 学院报名统计
    countCollegeRegist(row) {
      this.examId = row
      this.indexKey = 4
    },
    handleSelectionChange(val) {
      this.multipleSelection = val
    },
    handleSizeChange(val) {
      this.queryForm.pageSize_ = val
      this.getListData()
    },
    handleCurrentChange(val) {
      this.queryForm.pageNum_ = val
      this.getListData()
    },
    // 名单设置
    listSetting(rows) {
      this.dialogVisible = true;
      this.examIdrow=rows.id;
    },
    // 新增-取消按钮-关闭弹框
    closeListSetting() {
      this.dialogVisible = false
    },
    // 新增-关闭按钮-关闭弹框
    beforeClose() {
      this.dialogVisible = false
      // this.$refs['editListSet'].cancelOperate()
      // this.$refs['editListSet'].clearSereset()
    },
      deleteListSetting(val) {
      this.deleteIdList = val
    },
    // 编辑-确认按钮-确认名单
    confirmEditListSetting(val) {
      this.editConfirmData = val
      // this.examForm.listSet = val.map(value => {
      //   return {
      //     id: value.id,
      //     studentId: value.studentId,
      //     studentName: value.name,
      //     sex: value.sex,
      //     sexI18n: value.sexI18n,
      //     college: value.faculty,
      //     collegeI18n: value.facultyI18n,
      //     atSchoolStatus: value.leaveSchool,
      //     atSchoolStatusI18n: value.leaveSchoolI18n,
      //     studentStatus: value.registrationStatus,
      //     studentStatusI18n: value.registrationStatusI18n,
      //     enrolMethods: value.enrolMethods,
      //     enrolMethodsI18n: value.enrolMethodsI18n
      //   }
      // })
      this.dialogVisible = false
      // this.$refs.examForm.validateField('listSet')
    },
          // 取消
      cancelOperate() {
        if (!this.addConfirmData || this.addConfirmData.length === 0) {
          this.choosedListingData = []
          this.copyChoosedListingData = []
        } else {
          this.choosedListingData = JSON.parse(JSON.stringify(this.editConfirmData))
          this.setCurrentPageData()
        }
        this.activeName = 'studentListing'
        // if (this.activeName === 'studentListing') {
          this.studentQueryForm.condition.leaveSchoolList = []
          this.studentQueryForm.condition.registrationStatusList = []
          this.studentQueryForm.condition.enrolMethodsList = []
          this.studentQueryForm.condition.name = ''
          this.studentQueryForm.condition.gradeList = [this.calendarYear]
          // Object.keys(this.studentQueryForm.condition).forEach(key => this.studentQueryForm.condition[key] = '');
        // } else {
          this.choosedQueryForm.condition.leaveSchool = ''
          this.choosedQueryForm.condition.registrationStatus = ''
          this.choosedQueryForm.condition.enrolMethods = ''
          this.choosedQueryForm.condition.name = ''
          this.choosedQueryForm.condition.gradeList = []
          // Object.keys(this.choosedQueryForm.condition).forEach(key => this.choosedQueryForm.condition[key] = '');
        // }
        this.$refs['studentTable'].clearSelection()
        this.$refs['choosedTable'].clearSelection()
        this.studentQueryForm.pageNum_ = 1
        this.onSubmit()
        this.$emit('close-list-setting')
      },
  },
  watch: {
    auths: {
      handler(newVal) {
        if (newVal && Array.isArray(newVal) && newVal.length > 0) {
          newVal.some(item => {
            if (item.authCode === 'putonghua-createExam-add') {
              this.permitToAdd = true
            }
            if (item.authCode === 'putonghua-createExam-open') {
              this.permitToOpen = true
            }
            if (item.authCode === 'putonghua-createExam-close') {
              this.permitToClose = true
            }
            if (item.authCode === 'putonghua-createExam-edit') {
              this.permitToEdit = true
            }
            if (item.authCode === 'putonghua-createExam-studRegist') {
              this.permitToCountStuRegist = true
            }
            if (item.authCode === 'putonghua-createExam-collegeRegist') {
              this.permitToCountCollege = true
            }
          });
        }
      },
      deep: true,
      immediate: true
    }
  }
}
</script>
<style lang="scss" scoped>
  .status-container ::v-deep {
    .el-button {
      cursor: auto;
    }
    // .el-button--info {
    //   padding: 9px 21px;
    //   min-width: 0;
    // }
  }
  ::v-deep {
    .editor-custom-btn-container {
        display: none;
    }
}
</style>
